package servlet;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import decoder.ChineseDecoder;

import model.Member;
import factory.DaoFactory;

/**
 * Servlet implementation class RechargeServlet
 */
@WebServlet("/RechargeServlet")
public class RechargeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RechargeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		Member member = DaoFactory.getMemberDao().find(name);
		request.setAttribute("member", member);
		String address ="/jsp/Recharge.jsp?name=" + name;
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));

		float money = 0;
		try {
			money = Float.parseFloat(request.getParameter("money"));
		} catch (NumberFormatException e) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=MoneyError&name=" + name);
			return;
		}
		
		if (money <= 0) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=MoneyError&name=" + name);
			return;
		}

		Member member = DaoFactory.getMemberDao().find(name);

		if (member.getBalance() == -1) {
			if (money < 100) {
				response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=RechargeError&name=" + name);
				return;
			} else {
				member.setBalance(money);
			}
		} else {
			member.setBalance(member.getBalance() + money);
		}
		
		member.setLastRecharge(new Timestamp(Calendar.getInstance().getTimeInMillis()));

		boolean success = DaoFactory.getMemberDao().updateBalanceByName(member);
		if (success) {
			response.sendRedirect(request.getContextPath() + "/RechargeServlet?name=" + member.getName());
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=RechargeDatabaseError&name=" + name);
		}

	}

}
